package fun.tan90.easy.binlog.plugin.mqtt.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import fun.tan90.easy.binlog.plugin.mqtt.model.MqttClientParam;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.Objects;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/11/15 14:41
 */
@Slf4j
public class MqttPluginService implements PluginService {

    @Override
    public boolean test(String params) {
        MqttClientParam mqttClientParams = JSONUtil.toBean(params, MqttClientParam.class);
        MqttClient client = null;
        try {
            client = new MqttClient(mqttClientParams.getBroker(), mqttClientParams.getClientIdPrefix() + RandomUtil.randomNumbers(6), new MemoryPersistence());
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(mqttClientParams.getUsername());
            connOpts.setPassword(mqttClientParams.getPassword().toCharArray());
            connOpts.setMqttVersion(mqttClientParams.getMqttVersion());
            connOpts.setKeepAliveInterval(mqttClientParams.getKeepAliveInterval());
            connOpts.setConnectionTimeout(10);
            client.connect(connOpts);
            return client.isConnected();
        } catch (MqttException e) {
            e.printStackTrace();
            log.error("mqtt 连接测试失败，{}", e.getMessage());
            return false;
        } finally {
            if (!Objects.isNull(client) && client.isConnected()) {
                try {
                    client.disconnect();
                } catch (MqttException e) {
                    e.printStackTrace();
                    log.error("mqtt 连接关闭异常，{}", e.getMessage());
                }
            }
        }
    }
}
